%% peak_extract.m 
% a script to extract the peak wavelengths from the files output by
% lumerical fdtd, then create a new ascii file for origin import


peak_to_extract='scattering';

[filelist,pathname] = uigetfile('*.txt','Please select files to create peak list for','MultiSelect','on');

%% turn the file list into a cell array if it isn't already (next bit
%% expects one)
if ~iscell(filelist)
    if length(filelist)==1
        % no files were selected, so turn it into an empty array.
        filelist={};
        disp('no files selected.');
    else
        filelist={filelist};
    end
end

%%
if ~isempty(filelist)    
    n = size(filelist,2);
    peak=zeros(n,1);
    locstr=cell(size(peak));
    for ii=1:n
        filename=filelist{ii};
        disp(['extracting peak from file ' filename]);
        data=load(fullfile(pathname,filename));
        switch peak_to_extract
            case 'scattering'
                col=2;
            case 'absorption'
                col=3;
            case 'extinction'
                col=4;
            otherwise
                error('unrecognised column requested!');
        end
        [val ind] = max(data(:,col));
        peak(ii)=data(ind,1);

                loc=regexp(filename,'loc(?<loc>\d+)sweep_d(?<d>\d+)','names');
        if isempty(loc)
            loc=regexp(filename,'loc(?<loc>\d+)','names');
        end
        switch str2double(loc.loc)
            case 1
                if length(fields(loc))>1
                    locstr{ii}=loc.d;
                else
                    locstr{ii}='10';
                end
            case 2
                locstr{ii}='20';
            case 3
                locstr{ii}='40';
            case 4
                locstr{ii}='108';
            case 5
                locstr{ii}='corner';
            case 6
                locstr{ii}='no crystal';  % as no crystal used
        end
    end
    [outputfilename outpath] = uiputfile('*.txt','Select where to save the peaks file','peaks.txt');
    fid=fopen(fullfile(outpath, outputfilename),'w');
    fprintf(fid,['%% peak wavelengths for a selection of files in the directory: \n%% ' strrep(pathname,'\','\\')]);
    fprintf(fid,'%% filenames are listed below:\n');
    for ii=1:n
        fprintf(fid,['%% file ' filelist{ii} '\n']);
    end
    fprintf(fid,'\n%%location\tlambda\n');
    fprintf(fid,'%%(nm)\t(nm)\n');
    for ii=1:n
        fprintf(fid,[locstr{ii} '\t' num2str(peak(ii)) '\n']);
    end
    status=fclose(fid);
end